<template>
  <div class="basicsPage-container">
    <maskLayer :isLoading="isLoading"/>
    <div class="top-container" style="justify-content: end">
      <a-button type="primary" size="large" :icon="h(PlusOutlined)" @click="addUserClick">注册</a-button>
    </div>
    <div class="bot-container">
      <a-table v-if="tableDataList && tableDataList.length" :data-source="tableDataList" :scroll="{ y: 73+`vh` }"
               :pagination="{ pageSize: 15, showSizeChanger:false }">
        <a-table-column title="账号" data-index="account" :ellipsis="true"/>
        <a-table-column title="名称" data-index="username" :ellipsis="true"/>
        <a-table-column title="性别" data-index="gender" :ellipsis="true">
          <template #default="{ text }">
            {{ Gender[text as keyof typeof Gender] }}
          </template>
        </a-table-column>
        <a-table-column title="关联角色" data-index="action" :ellipsis="true">
          <template #default="{ record }">
            <a-button type="primary" size="large" @click="relevancyRoleClick(record)">关联角色</a-button>
          </template>
        </a-table-column>
        <a-table-column title="操作" data-index="action" :ellipsis="true" :width="450">
          <template #default="{ record }">
            <a-button type="primary" size="large" :icon="h(EditOutlined)" @click="editUserInfoClick(record)">修改信息
            </a-button>
            <a-button type="primary" size="large" style="margin-left: 10px" :icon="h(EditOutlined)"
                      @click="editUserPwdClick(record)">修改密码
            </a-button>
            <a-button type="primary" size="large" style="margin-left: 10px" danger :icon="h(DeleteOutlined)"
                      @click="deleteUserClick(record)">删除
            </a-button>
          </template>
        </a-table-column>
      </a-table>
      <div v-else class="page-notInfo">
        <div class="img-box">
          <img src="@/assets/emptyImg/empty.png" alt="">
        </div>
        <span>暂无信息</span>
      </div>
    </div>

    <a-modal :open="modalConfig.modalVisible" :title="modalConfig.modalTitle" centered :closable="false"
             :maskClosable="false">
      <template #footer>
        <a-button key="back" @click="modalCancelClick">取消</a-button>
        <a-popconfirm
            title="您登录的账号正是当前账号，确定修改吗？"
            ok-text="确定"
            cancel-text="放弃"
            :open="popConfirmIsOpen"
            @confirm="editConfirm(true,'info')"
            @cancel="popConfirmIsOpen = false"
        >
          <a-button key="submit" type="primary" @click="modalOperationClick">
            {{ modalConfig.modalTitle.substring(0, 2) }}
          </a-button>
        </a-popconfirm>
      </template>
      <a-form :model="modalFormData">
        <a-form-item label="昵称：">
          <a-input size="large" v-model:value="modalFormData.username" placeholder="请输入"/>
        </a-form-item>
        <a-form-item label="账号：">
          <a-input size="large" v-model:value="modalFormData.account" :disabled="modalConfig.modalTitle=='修改用户信息'"
                   placeholder="请输入"/>
        </a-form-item>
        <a-form-item label="密码：">
          <a-input size="large" v-model:value="modalFormData.password"
                   :placeholder="modalConfig.modalTitle.includes('注册')?'请输入':'不可见'"
                   :disabled="modalConfig.modalTitle=='修改用户信息'"/>
        </a-form-item>
        <a-form-item label="性别：">
          <a-select size="large" v-model:value="modalFormData.gender" :options="genderOptions"
                    placeholder="请选择性别"></a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal :open="modalConfig.modalVisible1" :title="modalConfig.modalTitle" centered :closable="false"
             :maskClosable="false">
      <template #footer>
        <a-button key="back" @click="modalCancelClick">取消</a-button>
        <a-popconfirm
            title="您登录的账号正是当前账号，确定修改吗？"
            ok-text="确定"
            cancel-text="放弃"
            :open="popConfirmIsOpen"
            @confirm="editConfirm(true,'password')"
            @cancel="popConfirmIsOpen = false"
        >
          <a-button key="submit" type="primary" @click="modalOperationClick">
            {{ modalConfig.modalTitle.substring(0, 2) }}
          </a-button>
        </a-popconfirm>
      </template>
      <a-form :model="modalFormData">
        <a-form-item label="原密码：">
          <a-input size="large" v-model:value="modalFormData.password" placeholder="请输入"/>
        </a-form-item>
        <a-form-item label="新密码：">
          <a-input size="large" v-model:value="modalFormData.newPassword" placeholder="请输入"/>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-drawer :destroyOnClose="true" :maskClosable="false" v-model:open="roleDrawerVisible"
              style="background-color: #0f1d51" title="关联角色信息" placement="right" @close="closeRoleDrawer"
              :keyboard="false">
      <div style="height: 10%;margin-bottom: 10%;">
        <a-form :model="userRoleDrawerInfo">
          <a-form-item label="注：" style="display: flex;align-items: center">
            <span
                style="color: red;margin-bottom: 20px">一个用户只能绑定一个角色，修改绑定角色需先删除已有绑定再新增</span>
          </a-form-item>
          <a-form-item label="注：" style="display: flex;align-items: center">
            <span
                style="color: red;margin-bottom: 20px">用户建议是要绑定角色的哟！</span>
          </a-form-item>
          <a-form-item label="角色名称：" style="display: flex;align-items: center">
            <a-select size="large" style="width: 85%;" v-model:value="userRoleDrawerInfo.selectRoleId"
                      placeholder="选择需关联的角色" :options="allRoleDataList"
                      :fieldNames="{ label: 'roleName', value: 'roleId' }"></a-select>
          </a-form-item>
          <a-form-item style="float:right;">
            <a-button key="submit" type="primary" @click="addUserRoleClick"
                      :disabled="userRoleDrawerInfo.drawerTableDataList.length!==0">新增
            </a-button>
          </a-form-item>
        </a-form>
      </div>
      <a-table style="position: relative" :data-source="userRoleDrawerInfo.drawerTableDataList" :scroll="{ y: 50+`vh` }"
               :pagination="{ pageSize: 15, showSizeChanger:false }">
        <a-table-column title="角色名称" :ellipsis="true">
          <template #default="{ record }">{{ record.roleName }}</template>
        </a-table-column>
        <a-table-column title="操作" data-index="action" :ellipsis="true">
          <template #default="{ record }">
            <a-button type="primary" size="large" shape="circle" danger @click="deleteUserRoleClick(record)"
                      :icon="h(DeleteOutlined)"/>
          </template>
        </a-table-column>
      </a-table>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import maskLayer from "@/components/MaskLayer/index.vue"
import {createVNode, h, onMounted, ref} from "vue";
import {
  DeleteOutlined, EditOutlined,
  ExclamationCircleOutlined, PlusOutlined
} from "@ant-design/icons-vue";
import {message, Modal} from 'ant-design-vue';
import {
  addUserRequest, deleteUser, getAllUser,
  updateUserInfoRequest, updateUserPasswordRequest
} from "@/api/basicsApi/systemManage/UserManage.ts";
import {Gender, genderOptions} from "@/enum/basicsEnum/systemMange";
import {getLoginInfo, systemLogout} from "@/utils/auth.ts";
import {
  addRoleUserRel, deleteRoleUserRel,
  getAllRole, getUserRoleByUserId
} from "@/api/basicsApi/systemManage/RoleManage.ts";
import {LoginInfo} from "@/interface/basicsInterface/systemManage";

const isLoading = ref(false)
const popConfirmIsOpen = ref<boolean>(false);// 弹窗确定/更新按钮是否显示确认弹窗
const tableDataList = ref([]) // 所有用户
const modalConfig = ref({
  modalVisible: false,
  modalVisible1: false,
  modalTitle: ""
})
const modalFormData = ref({
  userId: null,
  username: "",
  account: "",
  password: "",
  gender: undefined,
  newPassword: ""
})
const roleDrawerVisible = ref<boolean>(false); // 角色关联
const allRoleDataList = ref([]) // 所有角色
const userRoleDrawerInfo: any = ref({
  selectUserId: undefined,
  selectRoleId: undefined,
  drawerTableDataList: [],
  delRoleDataId: undefined
});
const whetherExitLog = ref<boolean>(false)
const loginInfo: LoginInfo = JSON.parse(getLoginInfo())

onMounted(async () => {
  await getAllUserFun()
  const {data} = await getAllRole()
  allRoleDataList.value = data
})

// 获取所有用户信息
async function getAllUserFun() {
  isLoading.value = true
  await getAllUser().then((res: any) => {
    tableDataList.value = res.data
    isLoading.value = false
  }).catch(() => {
    isLoading.value = false
  })
}

// 注册按钮
function addUserClick() {
  modalConfig.value.modalVisible = true
  modalConfig.value.modalTitle = "注册新用户"
  modalFormData.value = {
    userId: null,
    username: "",
    account: "",
    password: "",
    gender: undefined,
    newPassword: ""
  }
}

// 关联角色详情按钮
function relevancyRoleClick(record: any) {
  whetherExitLog.value = false
  roleDrawerVisible.value = true
  userRoleDrawerInfo.value.selectUserId = record.userId
  userRoleDrawerInfo.value.selectRoleId = undefined
  getUserRoleByUserIdFun()
}

// 用户新增角色关系--抽屉里的新增按钮
function addUserRoleClick() {
  if (userRoleDrawerInfo.value.selectRoleId === undefined) {
    message.error('请选择角色')
    return
  }
  addRoleUserRel(
      userRoleDrawerInfo.value.selectRoleId,
      userRoleDrawerInfo.value.selectUserId
  ).then((res: any) => {
    message.success(res.msg)
    getUserRoleByUserIdFun()
    userRoleDrawerInfo.value.selectRoleId = undefined
    whetherExitLog.value = userRoleDrawerInfo.value.selectUserId == loginInfo.userId
    console.log(whetherExitLog.value)
  })
}

// 获取用户绑定的角色Id
function getUserRoleByUserIdFun() {
  userRoleDrawerInfo.value.drawerTableDataList = []
  isLoading.value = true
  getUserRoleByUserId(userRoleDrawerInfo.value.selectUserId).then((res: any) => {
    allRoleDataList.value.forEach((element: any) => {
      if (element.roleId === res.data[0]) {
        userRoleDrawerInfo.value.drawerTableDataList.push({
          roleId: element.roleId,
          roleName: element.roleName
        });
      }
    });
    fileRoleList();
    isLoading.value = false
  }).catch(() => {
    isLoading.value = false
  })
}

// 根据表格里面的角色名称过滤所有角色信息
function fileRoleList() {
  allRoleDataList.value.forEach((roleInfo: any) => {
    roleInfo.disabled = false
  })
  userRoleDrawerInfo.value.drawerTableDataList.forEach((userHasRoleInfoName: { roleName: string, roleId: number }) => {
        const findRoleInfo: any = allRoleDataList.value.find((roleInfo: any) => {
          return roleInfo.roleName == userHasRoleInfoName.roleName
        })
        if (findRoleInfo) {
          findRoleInfo.disabled = true
        }
      }
  );
}

// 删除用户角色关系（用户绑定的角色）--抽屉里表格删除按钮
function deleteUserRoleClick(record: any) {
  allRoleDataList.value.forEach((option: any) => {
    if (record.roleName === option.roleName) {
      userRoleDrawerInfo.value.delRoleDataId = option.roleId;
    }
  });
  Modal.confirm({
    title: '你确定要删除此项吗?',
    icon: createVNode(ExclamationCircleOutlined),
    centered: true,
    onOk() {
      whetherExitLog.value = userRoleDrawerInfo.value.selectUserId == loginInfo.userId
      deleteRoleUserRel(userRoleDrawerInfo.value.delRoleDataId, userRoleDrawerInfo.value.selectUserId).then((res: any) => {
        message.success(res.msg)
        getUserRoleByUserIdFun()
      })
    },
    onCancel() {
      message.info('已取消删除操作');
    },
    class: 'test',
  });
}

// 弹窗取消按钮
function modalCancelClick() {
  modalConfig.value.modalVisible = false
  modalConfig.value.modalVisible1 = false
  modalConfig.value.modalTitle = ""
  modalFormData.value = {
    userId: null,
    username: "",
    account: "",
    password: "",
    gender: undefined,
    newPassword: ""
  }
}

// 弹窗操作按钮（注册/更新）
function modalOperationClick() {
  if (modalConfig.value.modalTitle.substring(0, 2) === '注册') {
    addUserRequest(modalFormData.value.account, modalFormData.value.password,
        modalFormData.value.username, modalFormData.value.gender
    ).then((res: any) => {
      message.success(res.msg)
      getAllUserFun()
    })
    modalConfig.value.modalVisible = false
  } else if (modalConfig.value.modalTitle === '修改用户信息') {
    if (loginInfo.userId === modalFormData.value.userId) {
      popConfirmIsOpen.value = true
    } else {
      editConfirm(false, 'info')
    }
  } else if (modalConfig.value.modalTitle === '修改用户密码') {
    if (loginInfo.userId === modalFormData.value.userId) {
      popConfirmIsOpen.value = true
    } else {
      editConfirm(false, 'password')
    }
  }
}

// 修改用户信息确认
function editConfirm(needExitSystem: Boolean, type: string) {
  if (type === 'info') {
    updateUserInfoRequest(
        modalFormData.value.userId,
        modalFormData.value.username,
        modalFormData.value.account,
        modalFormData.value.gender
    ).then((res: any) => {
      message.success(res.msg)
      getAllUserFun()
      modalConfig.value.modalVisible = false
      if (needExitSystem) {
        systemLogout()
      }
    }).catch(() => {
      modalConfig.value.modalVisible = false
    })
  } else {
    updateUserPasswordRequest(
        modalFormData.value.userId,
        modalFormData.value.password,
        modalFormData.value.newPassword
    ).then((res: any) => {
      message.success(res.msg)
      getAllUserFun()
      modalConfig.value.modalVisible1 = false
      if (needExitSystem) {
        systemLogout()
      }
    }).catch(() => {
      modalConfig.value.modalVisible1 = false
    })
    modalFormData.value.newPassword = ""
    modalFormData.value.password = ""
  }
}

// 修改用户信息
function editUserInfoClick(record: any) {
  modalConfig.value.modalVisible = true
  modalConfig.value.modalTitle = "修改用户信息"
  modalFormData.value = {
    userId: record.userId,
    username: record.username,
    account: record.account,
    password: record.password,
    gender: record.gender,
    newPassword: ""
  }
}

// 修改用户密码
function editUserPwdClick(record: any) {
  modalConfig.value.modalVisible1 = true
  modalConfig.value.modalTitle = "修改用户密码"
  modalFormData.value.password = record.password
  modalFormData.value.userId = record.userId
}

// 删除用户按钮
function deleteUserClick(record: any) {
  if (loginInfo.userId === record.userId) {
    modalConfirmFun(true, record.userId)
  } else {
    modalConfirmFun(false, record.userId)
  }
}

// 删除当前用户
function modalConfirmFun(needExitSystem: Boolean, userId: string) {
  let title: string = ""
  if (needExitSystem) {
    title = "当前账号正是您登录的账号，确定删除吗？"
  } else {
    title = '您确定要删除此项吗?'
  }
  Modal.confirm({
    title: title,
    icon: createVNode(ExclamationCircleOutlined),
    centered: true,
    onOk() {
      deleteUser(userId).then((res: any) => {
        message.success(res.msg)
        getAllUserFun()
        if (needExitSystem) {
          systemLogout()
        }
      })
    },
    onCancel() {
      message.info('已取消删除操作');
    },
    class: 'test',
  });
}

// 抽屉关闭按钮
function closeRoleDrawer() {
  if (whetherExitLog.value) {
    if (userRoleDrawerInfo.value.drawerTableDataList.length == 0) {
      quitLogin('您清空了当前登录账号的角色绑定，再次登录会没有可操作的菜单，请谨慎操作！', 'warn')
    } else {
      if (userRoleDrawerInfo.value.drawerTableDataList[0].roleId != loginInfo.roles[0].roleId) {
        quitLogin('您修改了当前登录账号的角色绑定，会退出登录！请重新登录', 'info')
      }
    }
  }
}

// 判断操作是否需要退出登录
function quitLogin(title: string, type: string) {
  Modal.confirm({
    title: title,
    icon: createVNode(ExclamationCircleOutlined),
    centered: true,
    cancelButtonProps: {
      style: {display: type === 'info' ? 'none' : 'inline-block'}
    },
    onOk() {
      systemLogout()
    },
    onCancel() {
      roleDrawerVisible.value = true
      message.info('已取消删除操作');
    },
    class: 'test',
  });
}
</script>

<style scoped lang="scss">
@use "@/styles/PageCss";
</style>
